﻿using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DynamicGeometry
{
    public class JoinTwoSegmentsCreator : Behavior
    {
        public override void MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var underMouse = Drawing.Figures.HitTest<FreePoint>(Coordinates(e));
            if (underMouse != null
                && underMouse.Dependents != null
                && underMouse.Dependents.Count() == 2)
            {
                LineBase line1 = underMouse.Dependents[0] as LineBase;
                LineBase line2 = underMouse.Dependents[1] as LineBase;

                if (line1 == null
                    || line2 == null
                    || line2.Dependencies.IsEmpty()
                    || line2.Dependencies.Count() != 2
                    )
                {
                    return;
                }

                var line2point1 = line2.Dependencies.ElementAt(0) as PointBase;
                var line2point2 = line2.Dependencies.ElementAt(1) as PointBase;

                if (line2point1 == null || line2point2 == null)
                {
                    return;
                }

                var line2OtherPoint = line2point1 == underMouse ? line2point2 : line2point1;

                using (Drawing.ActionManager.CreateTransaction())
                {
                    Drawing.Replace(line2, line1);
                    line2.Delete();
                    Drawing.Replace(underMouse, line2OtherPoint);
                    underMouse.Delete();
                }
            }
        }

        public override string Name
        {
            get { return "Join segments"; }
        }

        public override string HintText
        {
            get
            {
                return "Click a point between two segments to join the other two points.";
            }
        }

        public override FrameworkElement CreateIcon()
        {
            return IconBuilder.BuildIcon()
                .Line(0.25, 0.75, 0.4, 0.4)
                .Line(0.4, 0.4, 0.75, 0.25)
                .Point(0.25, 0.75)
                .Point(0.75, 0.25)
                .Canvas;
        }
    }
}